package com.sherlock.premssion.controller;

import com.sherlock.premssion.enums.REnum;
import com.sherlock.premssion.exception.SystemException;
import com.sherlock.premssion.filter.JwtFilter;
import com.sherlock.premssion.from.SysUserFrom;
import com.sherlock.premssion.model.SysUser;
import com.sherlock.premssion.repository.SysUserRepository;
import com.sherlock.premssion.service.SysUserService;
import com.sherlock.premssion.utils.*;
import com.sherlock.premssion.vo.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Map;

/**
 * author: rwj
 * date: 2018/4/7
 */
@Api(tags ="用户登录")
@RestController
@RequestMapping("/anno")
@Slf4j
public class AnnoController {

    @Autowired
    JWTUtil jwtUtil;

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    JwtFilter filter;

    @Autowired
    SysUserRepository userRepository;

    @Autowired
    SysUserService sysUserService;

    @ApiOperation(value = "用户登录")
    @PostMapping("/login")
    public R login(@RequestBody Map<String,String> map){

        Assert.isBlank(map.get("account"),"账号不能为空");
        Assert.isBlank(map.get("password"),"密码不能为空");

        String account = map.get("account");
        String password = map.get("password");
        SysUser user = userRepository.findByAccount(account);

        if(user == null){
            return RUtil.error(REnum.UNKNOWN_ACCOUNT.getCode(),REnum.UNKNOWN_ACCOUNT.getMessage());
        }
        if(user.getForbidden().equals(String.valueOf(1))){
            return RUtil.error(REnum.ACCOUNT_DISABLE.getCode(),REnum.ACCOUNT_DISABLE.getMessage());
        }
        //注册时将密码当做key，加密了用户名
        if(!PasswordUtil.decrypt(user.getPassword(),password,PasswordUtil.Salt).equals(account)){
            return RUtil.error(REnum.USERNAME_OR_PASSWORD_ERROR.getCode(),REnum.USERNAME_OR_PASSWORD_ERROR.getMessage());
        }
        String jwtToken = JWTUtil.sign(account, password);
        try {
            //存入redis
            redisUtil.set(account, jwtToken);

//            没有jwt的写法
//            Subject subject = ShiroUtil.getSubject();
//            UsernamePasswordToken token = new UsernamePasswordToken(account,password);
//            subject.login(token);
        }catch (Exception e){
           return RUtil.error(REnum.SYS_ERROR.getCode(),REnum.SYS_ERROR.getMessage());
        }
        return RUtil.success(jwtToken);
    }


    /**
     * 新增用户
     * @param sysUserFrom
     * @param bindingResult
     * @return
     */
    @ApiOperation(value = "新增用户")
//    @RequiresPermissions("sys:user:insert")
    @PostMapping("/saveUser")
    public R saveUser(@Valid @RequestBody SysUserFrom sysUserFrom,
                      BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            log.error("【新增用户】参数不正确:sysUserFrom={}"+ sysUserFrom);
            throw new SystemException(REnum.PARAM_ERROR.getCode(),bindingResult.getFieldError().getDefaultMessage());
        }

        return sysUserService.saveUser(sysUserFrom);
    }

    /**
     * 退出
     * @return
     */
    @ApiOperation(value = "用户退出")
    @GetMapping("/logout")
    public R logout(){
        ShiroUtil.logout();
        return RUtil.success();
    }

    /**
     * 登录页面
     * @return
     */
    @ApiOperation(value = "未登录跳转登录页面")
    @GetMapping("/notLogin")
    public R notLogin(){
       return RUtil.error(REnum.NOT_LOGIN.getCode(),REnum.NOT_LOGIN.getMessage());
    }
}
